package com.example.design.beautiful.unit_test.id_generator.refactor;

import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;

/**
 * @Description Id Generator that is used to generator random IDs
 * @date 2022/9/26 13:42
 * @Author liuzhihui
 * @Version 1.0
 */
@Slf4j
public class RandomIdGenerator implements LogTraceIdGenerator {

    /**
     * Generate the random ID. The IDs may be duplicated only in extreme situation.
     * @return an random ID
     */
    @Override
    public String generate() {
        String lastfieldOfHostName = getLastFieldOfHostName();
        long currentTimeMillis = System.currentTimeMillis();
        String randomString = generateRandomAlphameric(8);
        String id = String.format("%s-%d-%s", lastfieldOfHostName,
                currentTimeMillis, randomString);
        return id;
    }

    @VisibleForTesting
    public String generateRandomAlphameric(int length) {
        char[] randomChars = new char[length];
        int count = 0;
        Random random = new Random();
        while (count < length) {
            int maxAscii = 'z';
            int randomAscii = random.nextInt(maxAscii);
            boolean isDigit = randomAscii >= '0' && randomAscii <= '9';
            boolean isUppercase = randomAscii >= 'A' && randomAscii <= 'Z';
            boolean isLowercase = randomAscii >= 'a' && randomAscii <= 'z';

            if (isDigit || isUppercase || isLowercase) {
                randomChars[count] = (char) (randomAscii);
                ++count;
            }
        }
        return new String(randomChars);
    }

    private String getLastFieldOfHostName() {
        String lastfieldOfHostName = null;
        try {
            String hostName = InetAddress.getLocalHost().getHostName();
            lastfieldOfHostName = getLastSubstrSplittedByDot(hostName);
        } catch (UnknownHostException e) {
            log.warn("Failed to get the host name.", e);
        }

        return lastfieldOfHostName;
    }

    @VisibleForTesting
    public String getLastSubstrSplittedByDot(String hostName) {
        String[] tokens = hostName.split("\\.");
        String substrOfHostName = tokens[tokens.length - 1];
        return substrOfHostName;
    }

    public static void main(String[] args) {
        LogTraceIdGenerator logTraceIdGenerator = new RandomIdGenerator();
        System.out.println(logTraceIdGenerator.generate());
    }
}
